package com.heima.wemedia.service.impl;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.utils.AliyunOssUtils;
import com.heima.common.utils.UserThreadLocal;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /***
     * 图片类型
     */
    private List<String> imageType = Arrays.asList("png","jpg","jpeg","gif","bmp");
    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) throws Exception {
        //1.判断参数合法性
//1.1 判断文件大小是否为空
        long size = file.getSize();
        if (file.isEmpty() || size == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件内容不能为空");
        }
//1.2 判断文件是否超限
        if (size > 2048 * 1024) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件大小不能超过1M");
        }
        try {
//1.2 判断文件类型是否图片
            String type = FileTypeUtil.getType(file.getInputStream());
            if (!imageType.contains(type)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件类型必须是图片");
            }
//2.拼接唯一文件名
            String fileNameFull = IdUtil.fastSimpleUUID() + "." + type;
//3.上传文件到MinIO
            String url = fileStorageService.uploadImgFile("", fileNameFull, file.getInputStream());
//4. 保存素材
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);
//5. 响应数据
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
//6. 响应数据
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传出现问题");
        }
    }
    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
       //设置分页
        Page page = new Page(dto.getPage(),dto.getSize());
        //分页查询
        IPage<WmMaterial> page1 = this.lambdaQuery().eq(WmMaterial::getIsCollection, dto.getIsCollection())
                .page(page);

        //封装返回对象
        Long total = page1.getTotal();
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),total.intValue());
        result.setData(page1.getRecords());
        return result;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResponseResult del(Integer id) {
        //判断参数是否失效？？？
        if(id==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        //判断是否存在
        WmMaterial byId = this.getById(id);
        if(byId==null){
            return ResponseResult.errorResult(501,"数据不存在");
        }
        //判断是否被引用
       List<Integer> wmNewsMaterials= wmNewsMaterialMapper.selectListById(id);
        if(!CollectionUtils.isEmpty(wmNewsMaterials)){
            return ResponseResult.errorResult(501,"文件删除失败");
        }
        boolean b = this.removeById(id);
        if(!b){
            return ResponseResult.errorResult(501,"文件删除失败");
        }
        //删除成功则返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        //判断参数是否失效？？？
        if(id==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        //更新处理
        boolean update = this.lambdaUpdate().eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 0)
                .update();
        if(!update){
            return ResponseResult.errorResult(501,"参数失效");
        }
        return new ResponseResult(200,"操作成功");
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //判断参数是否失效？？？
        if(id==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        //更新处理
        boolean update = this.lambdaUpdate().eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 1)
                .update();
        if(!update){
            return ResponseResult.errorResult(501,"参数失效");
        }
        return new ResponseResult(200,"操作成功");
    }
}
